<template>
   <navbar />
  <div class="main-container drug-receive-management">
    <el-card class="tab-card">
      <el-tabs v-model="activeTab" class="single-tab">
        <el-tab-pane label="领药自动申请规则" name="receiveManage">
          <div class="settings-container">
            <div class="rule-tip">启用自动申请后，将在设定的时间自动帮病区向药房发送累计的领药申请</div>
            <div class="table-container">
              <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%"
                v-loading="tableLoading"
                @row-click="onRowClick"
                :row-class-name="rowClassName"
              >
                <el-table-column prop="wardName" label="病区名称" min-width="120" />
                <el-table-column prop="pharmacy" label="药房" width="120" />
                <el-table-column label="状态" width="100" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '未启用' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="仅申请当日药品" width="140" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.onlyToday ? 'warning' : 'info'">{{ row.onlyToday ? '启用' : '未启用' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="自动申请时间" min-width="180">
                  <template #default="{ row }">
                    <span v-if="row.times && row.times.length">每天 {{ row.times.join('、') }}</span>
                    <span v-else class="muted">未设置</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 分页（示意） -->
            <div class="queryParams-container">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="pageNum"
                @current-change="handlePageChange"
              />
            </div>

            <div class="action-row">
              <el-button type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
              <el-button class="ml-8" @click="handleCancel">取消</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 申领规则设置弹窗 -->
    <ApplyRuleDialog
      v-model:visible="dialogVisible"
      :model="editingModel"
      @confirm="onDialogConfirm"
      @disable="onDialogDisable"
    />
  </div>
</template>

<script setup name="DrugReceiveManagement">
// 组合式API
import { ref, reactive, onMounted } from 'vue'
import ApplyRuleDialog from './components/ApplyRuleDialog.vue'

// Tab 激活项（单Tab但保持统一接口）
const activeTab = ref('receiveManage')

// 表格数据与分页
const tableLoading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗控制与编辑模型
const dialogVisible = ref(false)
const editingIndex = ref(-1)
const editingModel = ref(null)

// 加载数据：本地存储优先，其次默认示例数据
function loadData() {
  tableLoading.value = true
  try {
    const cache = localStorage.getItem('drug-receive-rules')
    if (cache) {
      const parsed = JSON.parse(cache)
      tableData.value = parsed.items || []
      total.value = parsed.total || parsed.items?.length || 0
      return
    }
    // 默认数据：与原型图一致示例（病区1、本地药房、启用、未启用、每天 08:00）
    const defaults = [
      {
        wardName: '病区1',
        pharmacy: '本地药房',
        enabled: true,
        onlyToday: false,
        times: ['08:00']
      }
    ]
    tableData.value = defaults
    total.value = defaults.length
  } finally {
    tableLoading.value = false
  }
}

// 打开编辑弹窗
function openEdit(row, index) {
  // 关键节点：浅拷贝防止直接改动表格源数据
  editingModel.value = { ...row, wardNameReadonly: true }
  editingIndex.value = index
  dialogVisible.value = true
}

// 弹窗“确定”回调：更新表格并写入本地
function onDialogConfirm(payload) {
  // 提前返回：索引非法时直接结束
  if (editingIndex.value < 0) return
  tableData.value[editingIndex.value] = {
    wardName: payload.wardName,
    pharmacy: payload.pharmacy,
    enabled: payload.enabled,
    onlyToday: payload.onlyToday,
    // 避免重复计算：时间列表直接使用选值
    times: [...payload.times]
  }
  dialogVisible.value = false
  editingIndex.value = -1
}

// 弹窗“停用”回调：仅修改启用状态
function onDialogDisable() {
  if (editingIndex.value < 0) return
  const row = tableData.value[editingIndex.value]
  tableData.value[editingIndex.value] = { ...row, enabled: false }
  dialogVisible.value = false
  editingIndex.value = -1
}

// 分页切换（示意：仅更新当前页）
function handlePageChange(p) {
  pageNum.value = p
}

// 行点击：打开编辑弹窗
function onRowClick(row) {
  // 关键节点：通过对象引用在数据源中定位索引
  const idx = tableData.value.indexOf(row)
  // 提前返回：未找到索引
  if (idx < 0) return
  openEdit(row, idx)
}

// 行样式：统一加可点击的样式（指针样式）
function rowClassName() {
  return 'clickable-row'
}

// 保存：写入本地存储并提示
const saveLoading = ref(false)
async function handleSave() {
  try {
    saveLoading.value = true
    localStorage.setItem('drug-receive-rules', JSON.stringify({ items: tableData.value, total: total.value }))
    window?.$modal?.msgSuccess?.('保存成功')
  } catch (e) {
    console.warn('保存失败:', e)
    window?.$modal?.msgError?.('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 取消：恢复缓存或默认
function handleCancel() {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.drug-receive-management {
  .single-tab {
    --el-tabs-header-height: 40px;
  }

  .settings-container {
    padding: 8px 4px 16px;

    // 标题与提示一行展示
    .tip-line {
      display: flex;
      align-items: center;
      gap: 12px;
      margin: 8px 0 12px;
    }
    .section-title {
      font-weight: 600;
      color: var(--el-text-color-primary);
      white-space: nowrap;
    }
    .rule-tip {
      flex: 1;
      margin: 12px 0;
    }

    .muted {
      color: var(--el-text-color-secondary);
    }

    .action-row {
      margin-top: 12px;
      text-align: left;
    }

    .ml-8 {
      margin-left: 8px;
    }
  }

  // 可点击行：鼠标指针样式
  :deep(.el-table .clickable-row) {
    cursor: pointer;
  }
}
</style>
